extends CharacterBody2D

class_name Player

@onready var tileMap: TileMap = $'../TileMap'
@onready var path = $'../Path'
@onready var items = $'../Items'

const SPEED = 300.0
var way := []

func _physics_process(delta):
	# if Input.is_action_just_pressed("click"):
	# 	var current = position / tileMap.rendering_quadrant_size
	# 	var target = get_global_mouse_position() / tileMap.rendering_quadrant_size
	# 	way = path.find(current, target)

	if Input.is_action_just_pressed("ui_accept"):
		var item = items.findNearstItem(0, position)
		print('item', item.name, item.position)

	if len(way) > 0:
		var direction = global_position.direction_to(way[0])
		var time = path.getTime(position / tileMap.rendering_quadrant_size)
		velocity = direction * SPEED / time
		if position.distance_to(way[0]) < SPEED * delta:
			way.pop_front()
	else:
		velocity = Vector2(0, 0)

	move_and_slide()

# 向目标点移动
func moveTo(pos: Vector2):
	var current = position / tileMap.rendering_quadrant_size
	var target = pos / tileMap.rendering_quadrant_size
	way = path.find(current, target)
#  到达目标点
func isReached() -> bool:
	return len(way) == 0
